package models

import (
	"github.com/go-xorm/xorm"
)

type OpenInsDetail struct {
	ID            int    `xorm:"id pk autoincr"`
	OpenID        string `xorm:"openid"`
	Title         string `xorm:"title"`
	PassagewayID  string `xorm:"passagewayId"`
	DevicesOpenID string `xorm:"devicesOpenid"`
}

func (OpenInsDetail) TableName() string {
	return "OpenInsDetail"
}

type OpenData struct {
	Openid        string
	PassagewayId  string
	DevicesOpenid string
}

func OpenDataSelect(db *xorm.Engine) ([]*OpenData, error) {
	loggerl.Debugf("openDataSelect")
	var openDatas []*OpenData
	rows, err := db.QueryString("select oid.openid ,oid.passagewayId,oid.devicesOpenid  from OpenInsDetail oid , Monitor m  where  m.sCode  = oid.devicesOpenid")
	if err != nil {
		return nil, err
	}
	loggerl.Debugf("result: %v", rows)

	// result转换OpenData
	for _, row := range rows {
		openData := &OpenData{
			Openid:        row["openid"],
			PassagewayId:  row["passagewayId"],
			DevicesOpenid: row["devicesOpenid"],
		}
		openDatas = append(openDatas, openData)
	}
	return openDatas, nil
}

// TODO Insert into OpenInsDetail
func OpenInsDetailInsert(db *xorm.Engine, openid string, title string, passagewayId string, devicesOpenid string) error {
	loggerl.Debugf("OpenInsDetailInsert")
	loggerl.Debugf("openid: %s", openid)
	_, err := db.Exec("INSERT INTO OpenInsDetail (openid, title, passagewayId, devicesOpenid) VALUES (?, ?, ?, ?)", openid, title, passagewayId, devicesOpenid)
	if err != nil {
		return err
	}
	return nil
}

// TODO create table OpenInsDetail sqlserver 2008
func OpenInsDetailCreateTable(db *xorm.Engine) error {
	loggerl.Debugf("OpenInsDetailCreateTable")
	_, err := db.Exec("CREATE TABLE OpenInsDetail (id INT IDENTITY(1,1) PRIMARY KEY, openid VARCHAR(255), title VARCHAR(255), passagewayId VARCHAR(255), devicesOpenid VARCHAR(255))")
	if err != nil {
		return err
	}
	return nil
}

func OpenInsDetailTableExist(db *xorm.Engine) (bool, error) {
	loggerl.Debugf("OpenInsDetailTableExists")
	var exists bool
	result, err := db.QueryString("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OpenInsDetail'")
	if err != nil {
		return false, err
	}
	if len(result) > 0 {
		exists = true
	} else {
		exists = false
	}
	return exists, nil
}
